function [dtheta_mean, dtheta] = f_calc_gradient_mktwide( ...
    xnonlin_jt, ...
    dfull_jt,    ...
    share,       ...
    ddelta_dpi ...
)

product = share .* xnonlin_jt;
sum_product = sum(product);
expanded_sum_mkt = repmat(sum_product, size(xnonlin_jt, 1), 1, 1);        
dtheta = (dfull_jt.*share).*(xnonlin_jt - expanded_sum_mkt); 

% add ddelta_dpi
product = share .* ddelta_dpi;
sum_product = sum(product);
expanded_sum_mkt = repmat(sum_product, size(xnonlin_jt, 1), 1, 1);        
dtheta = dtheta + share.*(ddelta_dpi - expanded_sum_mkt); 

dtheta_mean = mean(dtheta,2);

end
